package Runde8;

public abstract class OneWayWorker implements Runnable {
		
		final protected Storage target;
		final private int wTime;
		final private int toGive;
		final protected Company comp;
		private int delivered;
		
		/**
		 * @precondition None of the arguments may be empty (null).
		 * @postcondition Creates a worker.
		 */
		public OneWayWorker(Storage target, int wTime, int toGive, Company comp) {
			this.target = target;
			this.wTime = wTime;
			this.toGive = toGive;
			this.comp = comp;
		}
		
		/**
		 * @postcondition Executed when Thread is started
		 */
		public void run() {
			while(comp.inOperation()) {
				work();
			}
		}
		
		/**
		 * @postcondition "Works" for a certain amount of time, waits until the target storage has enough space, then puts his load there. The counter for delivered goods is then increased.
		 */
		protected void work() {
			try {
				Thread.sleep(wTime);
				
				synchronized(target) {
					while(!target.tryPut(toGive)) {
							target.wait();
					}
				}
				delivered += toGive;
			} catch (InterruptedException e) { }
			
		}
		
		
		/**
		 * @postcondition Returns the objects-name and "delivered" goods.
		 */
		public String report() {
			return this + " - geliefert: " + delivered;
		}
		
		/**
		 * @postcondition Returns a readable identification of the worker.
		 */
		public abstract String toString();
		
	}